﻿#region License
/*
 * Copyright ©2011-2012 EasyMon Project
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *  
 */
#endregion

using System.Configuration;

namespace EasyMon.Common.Configuration
{
    public class DefaultConfigurationManager : IConfigurationManager
    {
        private static IConfigurationManager _default;

        /// <summary>
        /// Gets/sets the current configuration provider.
        /// The setting of a new provider is not thread safe by design (in order to avoid locking) 
        /// as it's intended mainly for unit testing, if you want to change the current provider
        /// it  must be done before any other code accessing it is executed
        /// Setting the property to null will force to use the DefaultConfigurationManager next time
        /// when the getter is called.
        /// </summary>
        public static IConfigurationManager Default
        {
            get { return _default ?? Nested.NestedDefault; }
            set { _default = value; }
        }

        public static IConfigurationManager GetExternal(string fileName)
        {
            return new ExternalConfiguration(fileName);
        }

        public static IConfigurationManager ReplaceDefaultBy(string fileName)
        {
            Default = GetExternal(fileName);

            return Default;
        }

        public string GetAppSetting(string name)
        {
            return ConfigurationManager.AppSettings[name];
        }

        public string GetConnectionString(string name)
        {
            return ConfigurationManager.ConnectionStrings[name].ConnectionString;
        }

        public T GetSection<T>(string sectionName) where T : ConfigurationSection
        {
            return ConfigurationManager.GetSection(sectionName) as T;
        }

        public object GetSection(string sectionName)
        {
            return ConfigurationManager.GetSection(sectionName);
        }

        static class Nested
        {
            internal static IConfigurationManager NestedDefault { get; private set; }

            static Nested()
            {
                NestedDefault = new DefaultConfigurationManager();
            }
        }
    }
}
